import 'package:cached_network_image/cached_network_image.dart';
import 'package:ecy_app_flutter/constant/constant.dart';
import 'package:ecy_app_flutter/routes/goodscart/model/EcyGoodsCartItemModel.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../../ecycommon/utils/EcyRandomUtil.dart';

class EcyGoodsCartItemWidget extends StatefulWidget {
  EcyGoodsCartItemWidget(this.model, this.onCheckValue, this.onOpeNumlValue,
      this.onSelectValue, this.onDelOneValue, this.editing, { super.key });
  final EcyGoodsCartItemModel model;
  final bool editing;
  _EcyGoodsCartItemWidgetState? state;
  //勾选或取消
  final ValueChanged<EcyGoodsCartItemModel> onCheckValue;
  //选择或减少数量
  final Function onOpeNumlValue;
  //选择某个购物
  final ValueChanged<EcyGoodsCartItemModel> onSelectValue;
  //删除某个谷子
  final ValueChanged<EcyGoodsCartItemModel> onDelOneValue;
  @override
  State<StatefulWidget> createState() {
    _EcyGoodsCartItemWidgetState _state = _EcyGoodsCartItemWidgetState(
        this.model,
        this.onCheckValue,
        this.onOpeNumlValue,
        this.onSelectValue,
        this.onDelOneValue,
        this.editing);
    state = _state;
    return _state;
  }

  reloadData(bool _editing) {
    state?.reloadData(_editing);
  }
}

class _EcyGoodsCartItemWidgetState extends State {
  EcyGoodsCartItemModel model;
  late final bool editing;
  //勾选或取消
  final ValueChanged<EcyGoodsCartItemModel> onCheckValue;
  //选择或减少数量
  final Function onOpeNumlValue;
  //选择某个购物
  final ValueChanged<EcyGoodsCartItemModel> onSelectValue;
  //删除某个谷子
  final ValueChanged<EcyGoodsCartItemModel> onDelOneValue;
  _EcyGoodsCartItemWidgetState(
      this.model,
      this.onCheckValue,
      this.onOpeNumlValue,
      this.onSelectValue,
      this.onDelOneValue,
      this.editing);
  @override
  void initState() {
    super.initState();
  }

  @override
  reloadData(bool _editing) {
    setState(() {
      editing = _editing;
    });
  }

  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        if (onCheckValue != null) {
          onCheckValue(model);
          setState(() {
            model = model;
          });
        }
      },
      child: Container(
        padding: EdgeInsets.only(left: 8.w, right: 8.w, top: 8.w, bottom: 8.w),
        height: 100.w,
        child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              GestureDetector(
                  onTap: () {
                    if (onSelectValue != null) {
                      if (model.selected != null) {
                        model.selected = !(model.selected!);
                        onSelectValue(model);
                      } else {
                        model.selected = true;
                        onSelectValue(model);
                      }
                      setState(() {
                        model = model;
                      });
                    }
                  },
                  child: Image(
                      image: AssetImage(model.selected ?? false
                          ? 'assets/images/login_checked.png'
                          : 'assets/images/login_unchecked.png'),
                      width: 20.w,
                      height: 20.w)),
              SizedBox(width: 8.w),
              Container(
                  width: 84.w,
                  height: 84.w,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(16.r)),
                    color: Colors.white, //设置背景色为黑色
                  ),
                  child: CachedNetworkImage(
                      width: 84.w,
                      height: 84.w,
                      imageUrl: model.image ?? "",
                      imageBuilder: (context, imageProvider) => Container(
                            decoration: BoxDecoration(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(8.r)),
                                image: DecorationImage(
                                    image: imageProvider, fit: BoxFit.cover)),
                          ),
                      // placeholder: (context, url) => CircularProgressIndicator(),
                      errorWidget: (context, url, error) => Container(
                          decoration: BoxDecoration(
                            borderRadius:
                                BorderRadius.all(Radius.circular(8.r)),
                            color: Colors.white, //设置背景色为黑色
                          ),
                          child:
                              Image.asset("assets/images/app_icon1024.png")))),
              SizedBox(width: 8.w),
              Expanded(
                  child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    model.productName ?? model.skuName ?? "--",
                    style: TextStyle(
                        color: const Color(0xFF262626),
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w500),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Center(
                          child: Text(
                        "¥${model.price}",
                        style: TextStyle(
                            color: const Color(0xFFF55F4E),
                            fontSize: 16.sp,
                            fontWeight: FontWeight.w900),
                      )),
                      Wrap(
                        direction: Axis.horizontal,
                        spacing: 4.w,
                        crossAxisAlignment: WrapCrossAlignment.center,
                        children: model.editing ?? false
                            ? [
                                GestureDetector(
                                  onTap: () {
                                    if (onDelOneValue != null) {
                                      onDelOneValue(model);
                                    }
                                  },
                                  child: Padding(
                                      padding: const EdgeInsets.only(bottom: 4),
                                      child: Image(
                                          image: const AssetImage(
                                              'assets/images/ic_cartgoods_del.png'),
                                          width: 20.w,
                                          height: 20.w)),
                                ),
                              ]
                            : [
                                GestureDetector(
                                    onTap: () async {
                                      if (onOpeNumlValue != null &&
                                          model.quantity != null) {
                                        if (model.quantity == 1) {
                                          // 判断是否删除
                                          bool? deleteFlag =
                                              await showDeleteConfirmDialog(
                                                  '确定移除该商品吗？');
                                          if (deleteFlag != null &&
                                              deleteFlag) {
                                            onDelOneValue(model);
                                          }
                                        } else if (model.quantity! > 1) {
                                          model.quantity = model.quantity! - 1;
                                          model.operation = 0;
                                          onOpeNumlValue(model);
                                          setState(() {
                                            model = model;
                                          });
                                        }
                                      }
                                    },
                                    child: Container(
                                        width: 24.w,
                                        height: 24.w,
                                        decoration: BoxDecoration(
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(4.r)),
                                          color: const Color(
                                              0xFFF5F5F5), //设置背景色为黑色
                                        ),
                                        child: Center(
                                            child: Text(
                                          "-",
                                          textAlign: TextAlign.center,
                                          style: TextStyle(
                                              color: const Color(0xD9000000),
                                              fontSize: 14.sp,
                                              fontWeight: FontWeight.w400),
                                        )))),
                                GestureDetector(
                                    onTap: () {},
                                    child: Container(
                                        width: 36.w,
                                        height: 24.w,
                                        decoration: BoxDecoration(
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(4.r)),
                                          color: const Color(
                                              0xFFF5F5F5), //设置背景色为黑色
                                        ),
                                        child: Center(
                                            child: Text(
                                          textAlign: TextAlign.center,
                                          (model.quantity != null
                                              ? model.quantity.toString()
                                              : "0"),
                                          style: TextStyle(
                                              color: const Color(0xD9000000),
                                              fontSize: 14.sp,
                                              fontWeight: FontWeight.w400),
                                        )))),
                                GestureDetector(
                                    onTap: () async {
                                      if (onOpeNumlValue != null) {
                                        model.quantity = (model.quantity ?? 0) + 1;
                                        model.operation = 1;
                                        bool success = await onOpeNumlValue(model);
                                        if(!success) {
                                          model.quantity = (model.quantity ?? 0) - 1;
                                        } else {
                                          setState(() {
                                            model = model;
                                          });
                                        }
                                      }
                                    },
                                    child: Container(
                                        width: 24.w,
                                        height: 24.w,
                                        decoration: BoxDecoration(
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(4.r)),
                                          color: const Color(
                                              0xFFF5F5F5), //设置背景色为黑色
                                        ),
                                        child: Center(
                                            child: Text(
                                          "+",
                                          textAlign: TextAlign.center,
                                          style: TextStyle(
                                              color: const Color(0xD9000000),
                                              fontSize: 14.sp,
                                              fontWeight: FontWeight.w400),
                                        ))))
                              ],
                      )
                    ],
                  )
                ],
              ))
            ]),
      ),
    );
  }

  // 弹出对话框
  Future<bool?> showDeleteConfirmDialog(String content) {
    return showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          // title: const Text(''),
          contentPadding: const EdgeInsets.all(0),
          backgroundColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8.0),
          ),
          content: SizedBox(
            height: 130,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Padding(
                  padding: const EdgeInsets.only(top: 20, bottom: 30),
                  child: Text(
                    content,
                    style: const TextStyle(fontSize: 18),
                  ),
                ),
                const Divider(height: 0, color: Color(0XFFdcdcdc)),
                SizedBox(
                  height: 50,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: DecoratedBox(
                          decoration: const BoxDecoration(
                              border: Border(
                            right: BorderSide(
                              width: 1.0,
                              color: Color(0XFFdcdcdc),
                            ),
                          )),
                          child: TextButton(
                            style: const ButtonStyle(
                              alignment: Alignment.center,
                            ),
                            child: const Text(
                              '我再想想',
                              style:
                                  TextStyle(fontSize: 18, color: Colors.black),
                            ),
                            onPressed: () =>
                                Navigator.of(context).pop(), // 关闭对话框
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: TextButton(
                          child: const Text(
                            '确定',
                            style: TextStyle(
                                fontSize: 18, color: Color(0xFFEA4B9B)),
                          ),
                          onPressed: () {
                            //关闭对话框并返回true
                            Navigator.of(context).pop(true);
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          actionsAlignment: MainAxisAlignment.spaceAround,
          actionsPadding: const EdgeInsets.all(0),
        );
      },
    );
  }

  @override
  void dispose() {
    // 清理控制器，避免内存泄漏
    super.dispose();
  }
}
